import { For, onMount, Show, createSignal, Signal } from "solid-js";
import { render } from "solid-js/web";
import { fetchAskData } from "./util/tools";

interface SrtContainerProps {
  season: string;
  elVideo: HTMLVideoElement;
  selectedRepeat: Signal<number>;
}

export default function SrtContainer(props: SrtContainerProps) {
  const get = 0, set = 1;
  const srts = createSignal<SRT[]>([]);
  const selectedEpisode = createSignal("");
  const loading = createSignal(false);
  const { season, elVideo, selectedRepeat } = props;
  const repeatCount = createSignal(0);
  let elEpisodes: HTMLSelectElement;

  function time2seconds(time: string): number {
    const h = time.slice(0, 2), m = time.slice(3, 5), s = time.slice(6);
    return parseInt(s) + parseInt(m) * 60 + parseInt(h) * 60 * 60;
  }
  async function gotoTime(time: string) {
    elVideo.currentTime = time2seconds(time);
    if (elVideo.paused)
      await elVideo.play();
  }

  async function repeateGotoTime(time: string, delayInSeconds: number) {
    const countLeft = repeatCount[get]();
    if (countLeft > 0) {
      repeatCount[set](countLeft - 1);
      await gotoTime(time);
      setTimeout(async () => await repeateGotoTime(time, delayInSeconds), delayInSeconds * 1000);
    }
  }

  async function handleDblClick(id: number, time: string) {
    if (repeatCount[get]() === 0) {
      const srtList = srts[get]();
      const size = srtList.length;
      let delay = 2;
      if (id < size) {
        const nextTime = srtList[id + 1].time;
        delay = time2seconds(nextTime) - time2seconds(time);
      }
      repeatCount[set](selectedRepeat[get]());
      await repeateGotoTime(time, delay);
    }
  }

  interface SRT {
    id: number;
    time: string;
    text1: string;
    text2: string;
  }

  function SRT(props: { item: SRT; }) {
    const { id, time, text1, text2 } = props.item;
    return <tr>
      <td><button
        onDblClick={async () => await handleDblClick(id, time)}
        onClick={async () => { if (repeatCount[get]() === 0) await gotoTime(time) }}>{time}</button></td>
      <td>{text1}</td>
      <td>{text2}</td>
      <td>{id}</td>
    </tr>
  }

  function EpisodeList(props: { list: string[] }) {
    const { list } = props;
    return <select ref={elEpisodes!} onChange={episodeChange}>
      <For each={list}>
        {item => <option value={item}>{item.slice(0, -4)}</option>}
      </For>
    </select>
  }


  onMount(async () => {
    const { list } = await fetchAskData("getEpisodes", { season }, true);
    const el = document.getElementsByClassName("episode-list")[0];
    if (el) {
      el.innerHTML = "";
      render(() => <EpisodeList list={list} />, el);
    }
    open(list[0]);
  });

  async function open(episode: string) {
    selectedEpisode[set](episode);
    loading[set](true);
    const { list } = await fetchAskData("getSrts", { season, episode: episode }, true);
    elVideo.src = "/movie/" + season + "/" + episode.replace(".srt", ".mkv");
    loading[set](false);
    srts[set](list);
  }
  async function episodeChange(e: Event) {
    const options = elEpisodes.options;
    const item = options[options.selectedIndex].value;
    open(item);
  }


  return (
    <>
      <Show when={loading[get]()}>
        <div class="msg">加载{selectedEpisode[get]()}...<img src="/img/loading.gif" alt="loading" /></div>
      </Show>
      <Show when={!loading[get]() && selectedEpisode[get]().length > 0}>
        <table class="table is-bordered is-striped is-hoverable">
          <thead><tr><th>时间点</th><th>字幕1</th><th>字幕2</th><th>序号</th></tr></thead>
          <tbody><For each={srts[get]()}>{item => <SRT item={item} />}</For></tbody>
        </table>
      </Show>
    </>
  );
}

